package com.sweetest.luffy.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sweetest.luffy.entity.DriveLine;
import com.sweetest.luffy.entity.LineRelation;
import com.sweetest.luffy.entity.User;
import com.sweetest.luffy.entity.UserLine;
import com.sweetest.luffy.page.Result;
import com.sweetest.luffy.service.IDriveLineService;
import com.sweetest.luffy.service.ILineRelationService;
import com.sweetest.luffy.service.IUserLineService;
import com.sweetest.luffy.service.IUserService;
import com.sweetest.luffy.util.GoogleMapUtil;
import com.sweetest.luffy.util.JwtUtil;
import com.sweetest.luffy.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "用户")
public class UserController {

    @Resource
    private IUserService userService;
    @Resource
    private IUserLineService userLineService;
    @Resource
    ILineRelationService lineRelationService;
    @Resource
    IDriveLineService driveLineService;

    @GetMapping(value = "/test")
    @ApiOperation(value = "提交行程")
    public void test(HttpServletRequest request) throws IOException {
//        LocalTestServerContext sc = new LocalTestServerContext("{\"status\" : \"OK\"}");
//        DistanceMatrix res= DistanceMatrixApi.newRequest(sc.context)
//                .origins(new LatLng(-31.9522, 115.8589), new LatLng(-37.8136, 144.9631))
//                .destinations(new LatLng(-25.344677, 131.036692), new LatLng(-13.092297, 132.394057))
//                .awaitIgnoreError();
        GoogleMapUtil.httpGet();
        System.out.println();
    }

    @PostMapping(value = "/login")
    @ApiOperation(value = "登录")
    public Result<Object> advertList(@RequestBody LoginVo vo) {

        if (CommonUtil.checkNull(vo.getPassword(), vo.getPhone(), vo.getType())) {
            return Result.ok(10400);
        }

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, vo.getPhone());
        List<User> list = userService.list(queryWrapper);
        String passMd5 = DigestUtils.md5DigestAsHex((vo.getPassword().trim()).getBytes());
        User user = new User();
        if (list.size() == 0) {
            user = new User();
            if (StringUtils.isNotBlank(vo.getLastName())) {
                user.setLastName(vo.getLastName());
            }
            if (StringUtils.isNotBlank(vo.getFirstName())) {
                user.setFirstName(vo.getFirstName());
            }
            if (StringUtils.isNotBlank(vo.getCarType())) {
                user.setCarType(vo.getCarType());
            }
            if (StringUtils.isNotBlank(vo.getColour())) {
                user.setColour(vo.getColour());
            }
            user.setPassword(passMd5);
            user.setPhone(vo.getPhone());
            user.setStatus(0);
            user.setType(vo.getType());
            userService.save(user);
            user.setToken(getToken(user));
        } else if (list.size() == 1) {
            user = list.get(0);
            if (!passMd5.equals(user.getPassword())) {
                return Result.ok(10400);
            }
            user.setToken(getToken(user));
        }

        return Result.ok(user);
    }


    @PostMapping(value = "/update")
    @ApiOperation(value = "修改用户信息")
    public Result<Object> advertList(HttpServletRequest request, @RequestBody User vo) {
        Integer id = JwtUtil.getUserId(request);
        vo.setId(id);
        if (CommonUtil.checkNull(vo.getCarType(), vo.getColour(), vo.getFirstName())) {
            vo.setStatus(1);
            vo.setType(2);
            userService.updateById(vo);
        }
        userService.updateById(vo);
        return Result.ok(vo);
    }


    @PostMapping(value = "/saveLine")
    @ApiOperation(value = "提交行程")
    public Result<Object> advertList(HttpServletRequest request, @RequestBody UserLine userLine) {
        Integer id = JwtUtil.getUserId(request);
        LambdaQueryWrapper<UserLine> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserLine::getUserId, id);
        queryWrapper.eq(UserLine::getStatus, 0);
        List<UserLine> lineList = userLineService.list(queryWrapper);
        if (lineList.size() > 0) {
            return Result.error(10201, "有未完成行程");
        }
        userLine.setCreateDate(new Date());
        userLine.setStatus(0);
        userLineService.save(userLine);
        OrderVo vo = line2Order(userLine);
        return Result.ok(vo);
    }

    @PostMapping(value = "/accept")
    @ApiOperation(value = "完成 1取消 2完成")
    public Result<Object> sure(HttpServletRequest request, @RequestBody AcceptVo acceptVo) {
        UserLine userLine = userLineService.getById(acceptVo.getId());
        userLine.setStatus(acceptVo.getStatus());
        userLineService.updateById(userLine);
        return Result.ok(userLine);
    }

    @GetMapping(value = "/getOrderList")
    @ApiOperation(value = "订单列表")
    public Result<List<OrderVo>> getOrderList(HttpServletRequest request) {
        Result<List<OrderVo>> result = new Result<>();
        Integer id = JwtUtil.getUserId(request);
        LambdaQueryWrapper<UserLine> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserLine::getUserId, id);
        List<UserLine> userLines = userLineService.list(queryWrapper);
        List<OrderVo> list = new ArrayList<>();
        for (UserLine userLine : userLines) {

            list.add(line2Order(userLine));
        }
        result.setData(list);
        return result;
    }

    private OrderVo line2Order(UserLine userLine) {

        OrderVo vo = new OrderVo();
        BeanUtil.copyProperties(userLine, vo);
        PointVo pointVo = new PointVo();
        pointVo.setULngStart(userLine.getStartLng());
        pointVo.setULatStart(userLine.getStartLat());
        pointVo.setULngEnd(userLine.getEndLng());
        pointVo.setULatEnd(userLine.getEndLat());
        if (userLine.getStatus() > 1) {
            LambdaQueryWrapper<LineRelation> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(LineRelation::getUserLineId, userLine.getId());

            LineRelation lineRelation = lineRelationService.list(lambdaQueryWrapper).get(0);
            User user = userService.getById(lineRelation.getDriverId());
            vo.setCarNumber(user.getCarNumber());
            vo.setColour(user.getColour());
            vo.setDriverId(user.getId());
            vo.setCarType(user.getCarType());
            DriveLine driveLine = driveLineService.getById(lineRelation.getDriverLineId());

            pointVo.setDLngEnd(driveLine.getEndLng());
            pointVo.setDLatEnd(driveLine.getEndLat());
            pointVo.setDLngStart(driveLine.getStartLng());
            pointVo.setDLatStart(driveLine.getStartLat());
        }
        vo.setPointVo(pointVo);
        return vo;
    }

    private String getToken(User user) {
        return JwtUtil.sign(user.getId(), user.getPhone(), "share");
    }
}
